package com.dragon.common.json.serializer;

import com.dragon.common.annotation.Sensitive;
import com.dragon.common.enums.DesensitizedType;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;

/**
 * 数据脱敏序列化
 *
 * @author dragon
 * @version 1.0
 * @date 2024/9/30 15:23
 */
public abstract class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private static final Logger log = LoggerFactory.getLogger(SensitiveJsonSerializer.class);

    private DesensitizedType desensitizedType;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (desensitization()) {
            jsonGenerator.writeString(desensitizedType.desensitized().apply(value));
        } else {
            jsonGenerator.writeString(value);
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        Sensitive annotation = beanProperty.getAnnotation(Sensitive.class);

        if (Objects.nonNull(annotation) && Objects.equals(String.class, beanProperty.getType().getRawClass())) {
            this.desensitizedType = annotation.desensitizedType();
            return this;
        }

        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }

    /**
     * 是否需要脱敏处理
     */
    protected abstract boolean desensitization();

}
